package com.neu.questionnaire_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neu.questionnaire_system.beans.ResponseEntity;
import com.neu.questionnaire_system.entity.User;
import com.neu.questionnaire_system.mapper.TenantMapper;
import com.neu.questionnaire_system.mapper.UserMapper;
import com.neu.questionnaire_system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.questionnaire_system.util.Constants;
import com.neu.questionnaire_system.util.EmailSender;
import com.neu.questionnaire_system.util.UUIDGenerator;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xingle
 * @since 2022-10-31
 * uuid自动生成，不用传入uid参数了，注意
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TenantMapper tenantMapper;

    /**
     * created by libo 2022-10-31
     *
     * @param map 从前端传入的data，注意map的key要时刻保持一致性
     * @return 返回一个结果给控制层
     */
    public ResponseEntity addUser(Map<String, Object> map) throws InvocationTargetException, IllegalAccessException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (map.get("userName") != null) {
            //需要写一个查询语句，判断用户是否存在，并返回一个值，用接收的值判断存在与否
            if (userMapper.queryExistUser(map) != 0) {
                responseEntity.setCode(Constants.FAIL_CODE);
                responseEntity.setMessage(Constants.USERNAME_REPEAT_MESSAGE);//表示用户已经存在不能创建
                return responseEntity;
            }
        }
        String tid = tenantMapper.findTidByName(map.get("tenantName").toString());
        map.put("tid", tid);
        String uid = UUIDGenerator.getOneUUID();//这个工具类不要导入错了，我自己写的在util包下
        User user = new User();
        map.put("uid", uid);//将生成的uid加入map中。
        map.put("isLogin", "1");
        map.put("isDeleted", "0");
        BeanUtils.populate(user, map);//用map中的元素封装user
        int res = userMapper.insert(user);//调用自动配置的插入方法，如果需要，可以使用下列注释的方法，新方法的数据库语句在resources包内的xml中
        //int res = userMapper.addUserInfo(map);
        responseEntity.setCode(Constants.SUCCESS_CODE);//封装状态码到返回的对象
        responseEntity.setMessage(Constants.ADD_MESSAGE);//封装状态消息到返回的对象
        return responseEntity;
    }

    /**
     * create by libo 租户主页展示用户信息
     *
     * @param map 传入的map
     * @return 返回包含用户列表信息的对象
     */
    public ResponseEntity showUser(Map<String, Object> map) {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setCode(Constants.SUCCESS_CODE);
        List<IPage<Map<String, Object>>> list = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tid", map.get("tid"));
        queryWrapper.eq("isDeleted", "0");
        int current = 1;
        long count = 0;
        while (count <= userMapper.selectCount(queryWrapper)) {
            IPage<Map<String, Object>> iPage = userMapper.showUser(new Page<>(current, Constants.PAGE_SIZE), map.get("tid").toString());
            list.add(iPage);
            current++;
            count += iPage.getSize();
        }
        responseEntity.setData(list);
        responseEntity.setMessage(Constants.SELECT_MESSAGE);
        return responseEntity;
    }

    /**
     * created by libo 删除用户
     *
     * @param map 被删除用户的用户名
     * @return 返回统一的封装对象
     */
    public ResponseEntity deleteUser(Map<String, Object> map) {
        ResponseEntity responseEntity = new ResponseEntity();
        if (userMapper.queryUserIsEmpty(map.get("userName").toString()) <= 0) {
            responseEntity.setCode(Constants.FAIL_CODE);//删除失败
            responseEntity.setMessage(Constants.DELETE_FAIL_MESSAGE);
            return responseEntity;
        } else {
            String uid = userMapper.queryUidByUserName(map.get("userName").toString());
            if (userMapper.queryClusterByUid(uid) > 0) {
                responseEntity.setCode(Constants.FAIL_CODE);
                responseEntity.setMessage(Constants.USERNAME_FAIL_DELETE_MESSAGE);//删除失败，当前用户还关联着群组
                return responseEntity;
            }
        }
        map.put("isDeleted", "1");
        int res = userMapper.deleteUser(map);
        if (res <= 0) {
            responseEntity.setCode(Constants.FAIL_CODE);//删除失败
            responseEntity.setMessage(Constants.DELETE_FAIL_MESSAGE);
            return responseEntity;
        }
        responseEntity.setCode(Constants.SUCCESS_CODE);
        responseEntity.setMessage(Constants.DELETE_MESSAGE);
        return responseEntity;
    }

    /**
     * created by libo 根据用户名查询用户
     *
     * @param map 传入的map
     * @return 统一的返回对象
     */
    public ResponseEntity findUserByUserName(Map<String, Object> map) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<IPage<Map<String, Object>>> list = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tid", map.get("tid"));
        queryWrapper.eq("isDeleted", "0");
        queryWrapper.like("userName", map.get("userName"));
        int current = 1;
        long count = 0;
        while (count <= userMapper.selectCount(queryWrapper)) {
            IPage<Map<String, Object>> iPage = userMapper.findUserByUserName(new Page<>(current, Constants.PAGE_SIZE), map.get("userName").toString(), map.get("tid").toString());
            list.add(iPage);
            current++;
            count += iPage.getSize();
        }
        responseEntity.setData(list);
        responseEntity.setCode(Constants.SUCCESS_CODE);
        responseEntity.setMessage(Constants.SELECT_MESSAGE);
        return responseEntity;
    }

    /**
     * created by libo 更新用户信息
     *
     * @param map 传入的数据
     * @return 返回统一的封装对象
     */
    public ResponseEntity updateUser(Map<String, Object> map) {
        ResponseEntity responseEntity = new ResponseEntity();
        String uid = userMapper.queryUidByUserName(map.get("userName").toString());
        if (userMapper.queryClusterByUid(uid)>0){
            responseEntity.setCode(Constants.FAIL_CODE);
            responseEntity.setMessage(Constants.USERNAME_FAIL_UPDATE_MESSAGE);
            return responseEntity;
        }else {
            if (userMapper.updateUser(map) > 0) {
                responseEntity.setCode(Constants.SUCCESS_CODE);
                responseEntity.setData("1");
                responseEntity.setMessage(Constants.UPDATE_MESSAGE);
            } else {
                responseEntity.setCode(Constants.FAIL_CODE);
                responseEntity.setMessage(Constants.UPDATE_FAIL_MESSAGE);
            }
        }
        return responseEntity;
    }

    /**
     * created by libo 修改用户信息确认，返回用户的uid
     * @param map 包含用户的名字userName
     * @return 返回统一的对象，包含用户的uid
     */
    public ResponseEntity update(Map<String,Object> map){
        ResponseEntity responseEntity = new ResponseEntity();
        String uid = userMapper.queryUidByUserName(map.get("userName").toString());
        if (userMapper.queryClusterByUid(uid)>0){
            responseEntity.setCode(Constants.FAIL_CODE);
            responseEntity.setMessage(Constants.USERNAME_FAIL_UPDATE_MESSAGE);
            return responseEntity;
        }else {
            responseEntity.setCode(Constants.SUCCESS_CODE);
            responseEntity.setCode(uid);
            responseEntity.setMessage("ok");
        }
        return responseEntity;
    }

    /**
     * created by libo 分页查询，管理员获取所有用户列表
     *
     * @return 返回封装用户内容的对象
     */
    public ResponseEntity showAllUser() {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setCode(Constants.SUCCESS_CODE);
        List<IPage<Map<String, Object>>> list = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isDeleted", "0");
        int current = 1;
        long count = 0;
        while (count <= userMapper.selectCount(queryWrapper)) {
            IPage<Map<String, Object>> iPage = userMapper.showAll(new Page<>(current, Constants.PAGE_SIZE));
            list.add(iPage);
            current++;
            count += iPage.getSize();
        }
        responseEntity.setData(list);
        responseEntity.setMessage(Constants.USER_SHOW_ALL_MESSAGE);
        return responseEntity;
    }

    /**
     * created by libo 分页查询，管理员模糊查询用户
     *
     * @param userName 输入的查询名字
     * @return 返回统一的分页后的结果
     */
    public ResponseEntity findAllUserLike(String userName) {
        ResponseEntity responseEntity = new ResponseEntity();
        List<IPage<User>> list = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("userName", userName);
        queryWrapper.eq("isDeleted", "0");
        int current = 1;
        long count = 0;
        while (count <= userMapper.selectCount(queryWrapper)) {
            IPage<User> iPage = userMapper.selectPage(new Page<>(current, Constants.PAGE_SIZE), queryWrapper);
            list.add(iPage);
            current++;
            count += iPage.getSize();
        }
        responseEntity.setData(list);
        responseEntity.setMessage(Constants.SELECT_MESSAGE);
        return responseEntity;
    }

    /**
     * created by libo 用户登录
     *
     * @param user 传入的user
     * @return 统一的对象
     */
    public ResponseEntity userLogin(User user) {
        ResponseEntity responseEntity = new ResponseEntity();
        User user1 = userMapper.queryUserInfo(user);
        if (user1 != null) {
            responseEntity.setCode(Constants.SUCCESS_CODE);
            responseEntity.setData(user1);
            responseEntity.setMessage(Constants.LOGIN_SUCCESS_MESSAGE);
            return responseEntity;
        } else {
            responseEntity.setCode(Constants.FAIL_CODE);
            responseEntity.setMessage(Constants.LOGIN_FAIL_MESSAGE);
            return responseEntity;

        }
    }

    /**
     * created by libo 管理员管理所选用户的登录权限
     *
     * @param isLogin  是否可登录，默认为1
     * @param userName 用户名字
     * @return 统一的返回结果
     */
    public ResponseEntity setIsLogin(String isLogin, String userName) {
        ResponseEntity responseEntity = new ResponseEntity();
        String uid = userMapper.queryUidByUserName(userName);
        responseEntity.setData(userMapper.setUserIsLogin(isLogin, uid));
        responseEntity.setMessage(Constants.UPDATE_MESSAGE);
        return responseEntity;
    }

    /**
     * created by tkj 发送用户验证码
     *
     * @param map 传入的数据（"email"-String,"code"-String）目标地址邮箱和验证码（用String）
     * @return 统一的对象
     */

    public ResponseEntity sendUserEmail(Map<String, Object> map) throws EmailException {
        ResponseEntity responseEntity = new ResponseEntity();
        String email = (String) map.get("email");
        String code = (String) map.get("code");
        EmailSender.simpleEmailSend(code, email);
        responseEntity.setData(1);
        responseEntity.setMessage(Constants.SEND_MESSAGE);
        responseEntity.setCode(Constants.SUCCESS_CODE);
        return responseEntity;
    }

}
